package com.edais.service.imp;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.edais.dao.CenterDao;
import com.edais.dao.RunningDao;
import com.edais.domain.OrderFormRecharge;
import com.edais.domain.RunningSignUpInfo;
import com.edais.service.RunningService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;

@Service

@Transactional
public class RunningServiceImpl implements RunningService {
	
	private static final Log logger = LogFactory.getLog(RunningServiceImpl.class);
	
	@Autowired
	private RunningDao runningDao;
	
	@Autowired
	private CenterDao centerDao;

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	@Override
	public void addRunningSignUpInfo(RunningSignUpInfo runningInfo)
			throws Exception {
		runningDao.addRunningSignUpInfo(runningInfo);
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	@Override
	public int updateRunningSignUpInfo(RunningSignUpInfo runningInfo)
			throws Exception {
		return runningDao.updateRunningSignUpInfo(runningInfo);
	}
	/**
	 * 查询剩余名额
	 * @param runingInfo
	 * @throws Exception
	 */
	@Override
	public String getSurplusPeople() {
		// TODO Auto-generated method stub
		return runningDao.getSurplusPeople();
	}
	/**
	 * 查询报名者信息(考虑是否过期)
	 * @param runingInfo
	 * @throws Exception
	 */
	@Override
	public List<RunningSignUpInfo> getEnrollInfo(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return runningDao.getEnrollInfo(map);
	}

	/**
	 * 连连支付回调
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	@Override
	public Map<String, Object> runningLLpayNotify(Map<String, Object> map) {
		Map<String, Object> rtnMap = new HashMap<String, Object>();

		String bindingReqNum = map.get("bindingReqNum").toString();
		logger.info("bindingReqNum:" + bindingReqNum);
		OrderFormRecharge isFalgFormRecharge = null;
		try{
			isFalgFormRecharge = centerDao
					.selectOrderFromRechargeByOrderId(bindingReqNum);
		} catch (Exception e2) {
			logger.info(e2.getMessage());
			rtnMap.put("rescode", Consts.ERROR_CODE);
			rtnMap.put("resmsg", e2.getMessage());
		}
		//String mobile = isFalgFormRecharge.getUser_id().toString();
		String noAgree = map.get("noAgree").toString();
		String moneyOrder = map.get("moneyOrder").toString();
		String oidPayBill = map.get("oidPayBill").toString();
		String reqStr = map.get("reqStr").toString();
		
		// 更新临时表订单信息
		OrderFormRecharge orderFormRecharge = new OrderFormRecharge();
		orderFormRecharge.setOrderform_id(bindingReqNum);
		orderFormRecharge.setOrder_id(oidPayBill);
		orderFormRecharge.setBack_time(new Date());// 反馈时间
		orderFormRecharge.setUpdate_time(new Date()); // 更新时间
		orderFormRecharge.setReceive_message(reqStr);// 返回报文
		orderFormRecharge.setBack_commen("连连支付-支付成功");// 反馈描述
		orderFormRecharge.setCore_status("CORE_SUC");

		orderFormRecharge.setRecharge_orderform_status("TRADE_SUCCESS");// 订单状态
		
		if (isFalgFormRecharge.getRecharge_orderform_status().equals(
				"TRADE_SUCCESS")) {
			rtnMap.put("rescode", Consts.SUCCESS_CODE);
			rtnMap.put("resmsg", "此订单已更新回调成功。");
		} else {
			try {
				int count = centerDao.updateOrderFromRecharge(orderFormRecharge);
				if (count == 0) {
					rtnMap.put("rescode", Consts.SUCCESS_CODE);
					rtnMap.put("resmsg", "未找到订单或此订单已更新回调成功。");
					logger.info("=============未找到订单或此订单已更新回调成功。===============");
					return rtnMap;
				}
				//更新running_sign_up_info表中数据
				Map<String,Object> runReqMap = new HashMap<String,Object>();
				runReqMap.put("isPay", "Y");
				//runReqMap.put("mobile", mobile);
				runReqMap.put("payOrderId",bindingReqNum);
				
				count = runningDao.updateInfoAfterLLpay(runReqMap);
				
				if(count==0){
					rtnMap.put("rescode", Consts.ERROR_CODE);
					rtnMap.put("resmsg", "更新奔跑报名表失败！");
					throw new RuntimeException("更新奔跑报名表失败");
				}
				//增加核心流水
				// 更新主账户信息
				System.out.println("=========================E310065CORE==========================");
				String transCode = "E310065";
				Map<String, Object> coreMap = new HashMap<String, Object>();
				coreMap.put("moneyOrder", moneyOrder);
				coreMap.put("applyId", isFalgFormRecharge.getId());
				String jsonStr;
				jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);
				String rtnStr = CommonUtil.getCoreValue(jsonStr);
				JSONObject jsonObject = JSONObject.fromObject(rtnStr);
				String rescode = jsonObject.getString("rescode");
				System.out.println("recode:"+rescode);
				if (rescode.equals(Consts.SUCCESS_CODE)) {
					rtnMap.put("rescode", Consts.SUCCESS_CODE);
					rtnMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
				} else {
					logger.info("插入流水失败！");
					rtnMap.put("rescode", Consts.ERROR_CODE);
					rtnMap.put("resmsg", "插入流水失败！");
					throw new RuntimeException("更新奔跑报名表失败！插入流水失败！");
				}
				
			} catch (Exception e1) {
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", e1.getMessage());
				return rtnMap;
			}
		}
		
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
		return rtnMap;
	}
	
	@Override
	public List<RunningSignUpInfo> getSignUpInInfo(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return runningDao.getSignUpInInfo(map);
	}
	/**
	 * 更新失败订单
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	@Override
	public Map<String, Object> marathonUpdateFaildOrder(Map<String, Object> map) throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		String mobile = map.get("mobile").toString();
		
		//根据用户手机号查询报名信息
		List<RunningSignUpInfo> runList = this.runningDao.getEnrollInfo(map);
		
		if(runList.size()>0){
			
			RunningSignUpInfo runInfo = runList.get(0);
			String payOrderId = runInfo.getPayOrderId();
			map.put("orderId", payOrderId);
			
			OrderFormRecharge faildOrder = this.centerDao.selectOrderFromRechargeByOrderId(payOrderId);
			
			if(faildOrder==null){
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "未查询到用户支付订单信息！");
				return rtnMap;
			}
			
			if (faildOrder.getRecharge_orderform_status()
					.equals("TRADE_SUCCESS")) {
				rtnMap.put("rescode", Consts.SUCCESS_CODE);
				rtnMap.put("resmsg", "此订单已更新回调成功。");
				return rtnMap;
			}
			faildOrder.setBack_time(new Date());// 反馈时间
			faildOrder.setUpdate_time(new Date()); // 更新时间
			faildOrder.setReceive_message(null);// 返回报文
			faildOrder.setBack_commen("连连支付-支付失败");// 反馈描述
			faildOrder.setCore_status("CORE_FAIL");
			faildOrder
					.setRecharge_orderform_status("TRADE_FAIL");// 订单状态
			int count = centerDao.updateOrderFromRecharge(faildOrder);
			
			if(count==0){
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "更新失败订单"+payOrderId+"失败！");
				return rtnMap;
			}
			rtnMap.put("rescode", Consts.SUCCESS_CODE);
			rtnMap.put("resmsg",  "更新失败订单"+payOrderId+"成功！");
		}else{
			rtnMap.put("rescode", Consts.ERROR_CODE);
			rtnMap.put("resmsg", "未查询到用户报名信息！");
			return rtnMap;
		}
		
		return rtnMap;
	}
}

